package com.example.demo.service.admin;

import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserAdminService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 添加用户
     *
     * @param user 用户信息
     * @return Boolean
     */
    public Boolean addUser(User user) {
        Boolean flag = true;
        try {
            if (user.getId() == null) {
                userMapper.save(user);
            } else {
                userMapper.updateByPrimaryKey(user);
            }
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        }
        return flag;
    }

    /**
     * 根据ID删除用户
     *
     * @param id 用户id
     * @return Boolean
     */
    public Boolean deleteUserById(Integer id) {
        Boolean falg = true;
        try {
            userMapper.deleteUser(id);
        } catch (Exception e) {
            e.printStackTrace();
            falg = false;
        }
        return falg;
    }

    /**
     * 根据ID查询用户
     *
     * @param id 用户id
     * @return User
     */
    public User selectUserById(Integer id) {
        User user = userMapper.selectByPrimaryKey(id);
        return user;
    }

    /**
     * 查询所有用户
     *
     * @return List<User>
     */
    public List<User> selectAll() {
        List<User> user = userMapper.selectAll();
        return user;
    }

    /**
     * 根据用户名查询用户
     *
     * @return List<User>
     */
    public List<User> selectByUsername(String userName) {
        List<User> user = userMapper.selectByUsername(userName);
        return user;
    }

    /**
     * 分页
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    public PageInfo<User> getPage(Integer pageNo, Integer pageSize) {
        //TODO 注释掉的部分是另一种写法，最下面return 后面的是JAVA8的写法
        PageHelper.startPage(pageNo, pageSize);
        List<User> list = userMapper.selectAll();
        return new PageInfo<>(list);
        // return PageHelper.startPage(pageNo, pageSize).doSelectPageInfo(() -> userMapper.selectAll());
    }

}
